<!-- 话题详情页面 -->
<template>
  <div class="topic-detail" ref="topicDetailRef">
    <!-- 全局加载效果 -->
    <van-loading v-if="isLoading" type="spinner" class="global-loading" />

    <!-- 内容区域，当加载时隐藏 -->
    <div v-else>
      <!-- 透明顶部导航栏 -->
      <div class="transparent-navbar" :class="{ scrolled: isScrolled }">
        <van-icon name="arrow-left" class="nav-icon" :color="isScrolled ? '#000' : '#fff'" @click="goBack" />
        <div class="nav-actions">
          <van-icon name="wechat" class="nav-icon" :color="isScrolled ? '#000' : '#fff'" @click="shareToWechat" />
          <van-icon name="friends-o" class="nav-icon" :color="isScrolled ? '#000' : '#fff'"
            @click="shareToWechatMoment" />
          <van-icon name="share-o" class="nav-icon" :color="isScrolled ? '#000' : '#fff'" @click="share" />
        </div>
      </div>

      <!-- 活动横幅 -->
      <div class="topic-banner">
        <van-image :src="topic_params.cover_image" fit="cover"></van-image>
      </div>

      <!-- 话题信息区域 -->
      <div class="topic-info">
        <div class="topic-header">
          <div class="topic-tag" v-if="topic_params.tag_list[0]">
            <van-icon :name="topic_params.tag_list[0].img" :style="{ background: topic_params.tag_list[0].bg }"
              class="hashTag"></van-icon>
            <span> {{ topic_params.name }} </span>
          </div>

          <div class="topic-body">
            <!-- 头像叠加区域 -->
            <div class="collectors" v-if="topic_params.users && topic_params.users.length > 0">
              <template v-for="(collector, index) in topic_params.users" :key="index">
                <img :src="proxyImageUrl(collector.p)" class="collector-avatar" />
              </template>
            </div>
            <div class="participants" v-if="topic_params.content_count">
              已有{{ topic_params.content_count }}人参与
            </div>
          </div>
        </div>
        <div class="topic-description">{{ topic_params.description }}~</div>
      </div>

      <!-- 内容列表 - 2列瀑布流 -->
      <div class="topic-content">
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <div class="card-grid">
            <div v-for="({ note }, index) in topicList" :key="index" class="card-item" @click="goToNote(note.id)">
              <!-- 卡片图片 -->
              <div class="card-image">
                <img :src="note.image_u" :alt="note.title" class="food-image" />
              </div>

              <!-- 卡片内容 -->
              <div class="card-content">
                <!-- 打卡信息 -->
                <div v-if="note.straight_text" class="check-in-badge">
                  <van-icon name="completed-o" class="completed-icon" />
                  <span>{{ note.straight_text }}</span>
                </div>
                <!-- 标题和描述 -->
                <div v-if="note.title" class="card-description">
                  {{ note.title }}
                </div>

                <!-- 用户信息和点赞 -->
                <div class="card-footer">
                  <div class="user-info">
                    <div class="username">{{ note.author?.n }}</div>
                    <div class="like-info">
                      <van-icon name="like-o" class="like-icon" />
                      <span class="like-count">{{ note.like_count }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!-- 底部操作栏 -->
      <div class="topic-footer">
        <van-button class="participate-btn" @click="participate">
          <van-icon :name="join.i"></van-icon>
          {{ join.t }}</van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted, useTemplateRef, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { fetchTopicDetail } from '@/api/index.js'
import { proxyImageUrl } from '@/tool/index.js'
// import { showToast } from 'vant'

// 加载状态
const isLoading = ref(true)

const route = useRoute()
const router = useRouter()

const id = computed(() => route.params.id) // 话题id
const pageNumber = ref(1)
const limit = ref(20)
const offset = computed(() => (pageNumber.value - 1) * limit.value)

const loading = ref(false)
const finished = ref(false)

const isInit = ref(true) //初始化

//当前返回列表数量
const currentResponseLength = ref(0)

// 滚动状态
const topicDetail = useTemplateRef('topicDetailRef')
const isScrolled = ref(false)
const bannerHeight = ref(0)

// 话题列表数据
const topicList = ref([])

const topic_params = ref({}) //话题参数

const join = ref({}) //参与话题按钮

const getTopicDetail = async (id, offset, limit, isInit) => {
  try {
    loading.value = true

    const {
      state,
      result: { topic, list, floating_button },
    } = await fetchTopicDetail(id, offset, limit)

    if (state === 'success') {
      currentResponseLength.value = list.length
      //是否有数据
      if (currentResponseLength.value > 0) {
        // 如果是初始化加载
        if (isInit) {
          topicList.value = list
          topic_params.value = topic
          join.value = floating_button
        } else {
          topicList.value = [...topicList.value, ...list]
        }
      } else {
        // 没有更多数据
        finished.value = true
      }
    } else {
      console.log('加载话题详情失败')
      pageNumber.value--
      loading.value = false
    }
  } catch (error) {
    console.log('加载话题详情失败:', error)
    pageNumber.value--
  } finally {
    loading.value = false
    isLoading.value = false
  }
}

watch(
  () => id.value,
  async (newId) => {
    if (newId) {
      //加载API
      isInit.value = true
      pageNumber.value = 1
      console.log('pageNumber', pageNumber.value)
      await getTopicDetail(newId, offset.value, limit.value, isInit.value)
    }
  },
  { immediate: true },
)

const onLoad = async () => {
  if (finished.value) {
    loading.value = false
    return
  }
  pageNumber.value++
  isInit.value = false
  console.log('pageNumber', pageNumber.value)
  await getTopicDetail(id.value, offset.value, limit.value, isInit.value)
}

const goToNote = (id) => {
  router.push({ path: `/note/${id}` })

  nextTick(() => {
    window.scrollTo(0, 0)
  })
}

// 返回上一页
const goBack = () => {
  router.back()
  nextTick(() => {
    window.scrollTo(0, 0)
  })
}

// 分享到微信
const shareToWechat = () => {
  showToast('分享到微信功能开发中')
}

// 分享到微信朋友圈
const shareToWechatMoment = () => {
  showToast('分享到微信朋友圈功能开发中')
}

// 分享功能
const share = () => {
  showToast('分享功能开发中')
}

// 参与活动
const participate = () => {
  showToast('参与活动功能开发中')
}

// 滚动监听函数
const handleScroll = () => {
  if (!topicDetail.value) return

  const scrollTop = topicDetail.value.scrollTop
  const bannerOffsetTop = bannerHeight.value

  // 当滚动超过活动横幅时，导航栏图标变为黑色
  isScrolled.value = scrollTop > bannerOffsetTop
}

// 计算活动横幅高度
const calculateBannerHeight = () => {
  const bannerElement = document.querySelector('.topic-banner')
  if (bannerElement) {
    bannerHeight.value = bannerElement.offsetHeight
  }
}

onMounted(() => {
  // 页面初始化逻辑
  // 计算banner高度
  calculateBannerHeight()

  // 添加滚动监听
  if (topicDetail.value) {
    topicDetail.value.addEventListener('scroll', handleScroll)
  }

  // 监听窗口大小变化，重新计算横幅高度
  window.addEventListener('resize', calculateBannerHeight)
})

onUnmounted(() => {
  // 清理事件监听
  if (topicDetail.value) {
    topicDetail.value.removeEventListener('scroll', handleScroll)
  }
  window.removeEventListener('resize', calculateBannerHeight)
});
</script>

<style scoped lang="scss">
.topic-detail {
  height: 100vh;
  padding-bottom: 80px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }

  .global-loading {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 9999;
  }
}

/* 透明顶部导航栏样式 */
.transparent-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: transparent;
  z-index: 1000;
  transition: all 0.3s ease;
}

.transparent-navbar.scrolled {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.nav-actions {
  display: flex;
  gap: 16px;
}

.nav-icon {
  width: 24px;
  height: 24px;
  font-size: 20px;
  color: #000;
  cursor: pointer;
  transition: all 0.2s ease;
}

.nav-icon:hover {
  opacity: 0.7;
  transform: scale(0.95);
}

/* 活动横幅样式 */
.topic-banner {
  position: relative;
  /* 给固定导航栏留出空间 */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-icon {
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.banner-content {
  flex: 1;
  text-align: center;
  padding: 0 12px;
}

.banner-title {
  margin: 0 0 8px 0;
  line-height: 1.2;
}

.title-main {
  display: block;
  font-size: 20px;
  font-weight: bold;
  color: #ff6347;
  text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.8);
  margin-bottom: 4px;
}

.title-sub {
  display: block;
  font-size: 16px;
  font-weight: normal;
  color: white;
}

.banner-reward {
  font-size: 14px;
  color: white;
  opacity: 0.9;
}

.reward-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  background: #ff6347;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: bold;
  margin: 0 4px;
}

.share-icon {
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

/* 话题信息区域 */
.topic-info {
  background: white;
  padding: 16px 10px;
}

.topic-header {
  // display: flex;
  // justify-content: space-between;
  // align-items: center;
  margin-bottom: 8px;
}

.topic-tag {
  color: #000;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  .hashTag {
    border-radius: 50%;
    padding: 4px;
    margin-right: 10px;
  }

  span {
    font-size: 16px;
    font-weight: bold;
  }
}

.topic-body {
  display: flex;
  align-items: center;

  .collectors {
    display: flex;
    align-items: center;
    margin-right: 12px;

    .collector-avatar {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      object-fit: cover;
      margin-right: -12px;
      border: 1px solid #fff;

      &:first-child {
        // margin-right: 4px;
      }
    }
  }

  .participants {
    font-size: 14px;
    color: #666;
  }
}

.topic-description {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

/* 内容区域 */
.topic-content {
  padding: 0 5px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  align-items: start;
}

.card-item {
  background: white;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
  height: fit-content;
}

.card-item:hover {
  transform: translateY(-2px);
}

.card-image {
  position: relative;
  width: 100%;
  aspect-ratio: 3/4;
  overflow: hidden;
}

.food-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-content {
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.check-in-badge {
  color: white;
  font-size: 10px;
  border-radius: 8px;
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  margin-bottom: 4px;

  span {
    font-size: 12px;
    color: #666;
  }
}

.check-in-placeholder {
  margin-bottom: 4px;
  min-height: 20px;
  /* 与check-in-badge保持一致的高度 */
}

.completed-icon {
  background: rgba(0, 128, 0, 0.8);
  border-radius: 50%;
  padding: 2px;
  margin-right: 5px;
}

.card-description {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  margin-top: 4px;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: auto;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.username {
  font-size: 12px;
  color: #666;
}

.like-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.like-icon {
  font-size: 14px;
  color: #999;
}

.like-count {
  font-size: 12px;
  color: #999;
}

/* 底部操作栏 */
.topic-footer {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}

.participate-btn {
  width: 100%;
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 24px;
  padding: 0px 24px;
  font-size: 12px;
  font-weight: bold;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
  transition: all 0.2s ease;
}

.participate-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(255, 77, 79, 0.4);
}
</style>
